package com.ipodget

import static org.apache.lucene.index.IndexWriter.MaxFieldLength.LIMITED
import static org.apache.lucene.document.Field.Store.YES
import static org.apache.lucene.document.Field.Index.ANALYZED
import static org.apache.lucene.document.Field.Index.NOT_ANALYZED

import org.cmc.music.myid3.MyID3
import org.cmc.music.metadata.IMusicMetadata

import org.apache.lucene.analysis.standard.StandardAnalyzer
import org.apache.lucene.index.IndexWriter
import org.apache.lucene.document.Document
import org.apache.lucene.document.Field

public class IpodIndexer {
	Ipod ipod
	
	public IpodIndexer(Ipod ipod){
		this.ipod = ipod
	}
	
	def index = { logger ->
		logger?.call "Starting indexing..."
		def id3Reader = new MyID3()
		def indexWriter = new IndexWriter(ipod.indexRoot, new StandardAnalyzer(), true, LIMITED)
		ipod.crawl { file ->
			if (file.name =~ /.mp3$/) {
				IMusicMetadata song = id3Reader.read(file).simplified;
				if(song){
					def document = new Document()
					song.each { document.add(new Field(it.key, it.value as String, YES, NOT_ANALYZED)) }
					document.add(new Field("filename", file.canonicalPath, YES, NOT_ANALYZED))
					document.add(new Field("all", "${song.artist} ${song.album} ${song.title}", YES, ANALYZED))
					indexWriter.addDocument document
					logger?.call "Added: ${song.artist} ${song.album} ${song.title}"					
				} else {
					logger?.call "File with no metadata: $file"
				}
	        }
		}
		int documentsIndexed = indexWriter.docCount()
		logger?.call "Finished crawling. Songs found: $documentsIndexed"
		logger?.call "Optimizing index..."
		indexWriter.optimize()
		indexWriter.close()
		logger?.call "Finished indexing..."
	}	
}